
Page({
  data: {
    carts: [],
    allChecked:"",
    sum:""
  },
  onLoad() {
    var url = `http://124.70.134.133:3000/cart`;
    wx.request({
      url,
      method: "GET",
      success: (res) => {
        var allChecked = res.data.every(item=>{
          return item.isSelected;
        })
        // this.handleNum()
        this.setData({
          carts: res.data,
          allChecked
        })
        this.handleSum()
      }
     
    })
  },
  handleNum(event){
    var carts = this.data.carts;
    var {aid} = event.currentTarget.dataset;
    carts.forEach(item=>{
      if(item.id==aid){
        item.productCount = event.detail
      }
    })
    this.setData({
      carts
    })
    this.handleSum()
  },
  handleSelect(e){
    var carts = this.data.carts;
    var {aid} = e.currentTarget.dataset;
    carts.forEach(item=>{
      if(item.id==aid){
        // 给每个子项加了isSelected属性
        item.isSelected = e.detail;
      }
    })
    console.log(carts);
    // 更改item的checked allChecked
    var allChecked = carts.every(item=>{
      return item.isSelected
    }) 
    this.setData({
      carts,
      allChecked
    })
    this.handleSum()
  },
  handleAll(e){
    var carts = this.data.carts;
    carts.forEach(item=>{
      item.isSelected = e.detail;
    })
    this.setData({
      carts,
      allChecked:e.detail,
    })
    this.handleSum()
  },
  handleSum(){
    var sum = 0;
    var carts = this.data.carts;
    carts.forEach(item=>{
      if(item.isSelected){
        sum += (item.productPrice)*(item.productCount)   
     }
    })
    this.setData({
      sum:sum*100,
    })
  }
})